package com.android.manghe.quickpay.view;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class SpaceText implements TextWatcher {

    private EditText etSpace;
    int beforeTextLength = 0;
    int onTextLength = 0;

    public SpaceText(EditText etSpace) {
        super();
        this.etSpace = etSpace;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        beforeTextLength = s.length();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String str = etSpace.getText().toString();
        onTextLength = str.length();
        if (onTextLength > beforeTextLength) {
            //输入
            if (str.length() % 5 == 0) {
                etSpace.setText(new StringBuffer(str).insert(str.length() - 1,
                        " ").toString());
                etSpace.setSelection(etSpace.getText().length());
            }
        } else {
            //删除
            if (str.startsWith(" ")) {
                etSpace.setText(new StringBuffer(str).delete(onTextLength - 1,
                        onTextLength).toString());
                etSpace.setSelection(etSpace.getText().length());
            }
        }
    }
}
